package com.mercenary.wein.screenControl.ui.batch;


import com.mercenary.wein.screenControl.bean.DeviceBean;
import com.mercenary.wein.screenControl.command.CommandTool;
import com.mercenary.wein.screenControl.ui.util.Constants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;


public class ImportAddressBook extends JDialog {
    Log log = LogFactory.getLog(ImportAddressBook.class);


    GroupCheckBoxPanel J1 = new GroupCheckBoxPanel();
    JPanel J2 = new JPanel();
    JPanel J3 = new JPanel();


    //J2的面板
    JPanel J9 = new JPanel();
    JScrollPane J10 = new JScrollPane();
    JPanel J11 = new JPanel();
    JPanel J12 = new JPanel();
    JPanel J13 = new JPanel();
    static JFrame jf = new JFrame();

    public ImportAddressBook() {
        super(jf, "导入通讯录");
        setBounds(200, 100, 700, 550);
        setLayout(new BorderLayout());
        setVisible(true);
        add(J1, BorderLayout.WEST);
        add(J2, BorderLayout.CENTER);
        add(J3, BorderLayout.EAST);
        J1.setPreferredSize(new Dimension(180, 550));//设置大小
        J1.setBackground(Color.WHITE);
        J2.setPreferredSize(new Dimension(270, 550));
        J2.setBackground(Color.WHITE);
        J2.add(J9);
        J2.add(J10);
        J9.setPreferredSize(new Dimension(250, 50));
        J10.setPreferredSize(new Dimension(250, 500));
        J10.setBackground(Color.pink);
        J3.setPreferredSize(new Dimension(250, 550));//设置大小
        J3.setBackground(Color.WHITE);
        Border titleBorder2 = BorderFactory.createTitledBorder("从文件导入号码");
        J2.setBorder(titleBorder2);
        Border titleBorder3 = BorderFactory.createTitledBorder("导入");
        J3.setBorder(titleBorder3);

        final JLabel j2 = new JLabel("已准备号码数:0");
        //J2的组件
        //初始化表格
        Vector<String> columnNames = new Vector<String>();
        columnNames.add("序号");
        columnNames.add("手机号码");
        Vector<List<String>> columnData = new Vector<List<String>>();
        DefaultTableModel dm = new DefaultTableModel(columnData, columnNames);
        final JTable friends = new JTable(dm);
        final List<String> phoneNums = new ArrayList<String>();
        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
        J10.setViewportView(friends);
        tcr.setHorizontalAlignment(SwingConstants.CENTER);// 这句和上句作用一样
        friends.setDefaultRenderer(Object.class, tcr);
        friends.setPreferredScrollableViewportSize(new Dimension(100, 20));
        J10.validate();

        JButton B4 = new JButton("选择文件");
        B4.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser(Constants.RepertoryPath);// 以c:\\winnt为打开文件为对话框的默认路径
                // 利用addChoosableFileFilter()方法加入欲过滤的文件类型,使用addChoosableFileFilter()可以加入多种文件类型,
                // 若你只需要过滤出一种文件类型,可使用setFileFilter()方法.
                fileChooser.addChoosableFileFilter(new JavaFileFilter("class"));
                fileChooser.addChoosableFileFilter(new JavaFileFilter("java"));
                int result = fileChooser.showOpenDialog(jf);
                // /如果选择确定按钮的话，那么则可以打开现有的文件
                if (result == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                    Vector<String[]> address = readFile(file);
                    phoneNums.removeAll(phoneNums);

                    DefaultTableModel dm = ((DefaultTableModel) friends.getModel());
                    while (dm.getRowCount() > 0) {
                        dm.removeRow(0);
                    }
                    for (String[] s : address) {
                        dm.addRow(s);
                        phoneNums.add(s[1]);
                    }
                    dm.fireTableDataChanged();
                    j2.setText("已准备号码数:" + address.size());
                    j2.repaint();
                    //label.setText("你选择了:" + file.getName() + "文件");
                }
                // /否则如果单击取消的话，那么就会在标签中显示"你没有选取文件"
                else if (result == fileChooser.CANCEL_OPTION) {
                }
            }
        });
        JButton B5 = new JButton("清空数据");
        B5.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                DefaultTableModel dm = ((DefaultTableModel) friends.getModel());
                while (dm.getRowCount() > 0) {
                    dm.removeRow(0);
                }
                dm.fireTableDataChanged();
                phoneNums.removeAll(phoneNums);
                j2.setText("已准备号码数:" + 0);
                j2.repaint();
            }
        });
        J9.add(B4);
        J9.add(B5);
        J9.validate();


        //J3组件
        //J3.setLayout();
        SelectedNumLabel j1 = new SelectedNumLabel();
        J1.registerObserver(j1);

        J11.setPreferredSize(new Dimension(250, 100));
        J12.setPreferredSize(new Dimension(250, 100));
        J13.setPreferredSize(new Dimension(250, 150));
        J11.setLayout(new GridLayout(2, 1));
        J13.setLayout(new GridLayout(3, 1));
        J3.add(J11);
        J3.add(J12);
        J3.add(J13);
        //是否清空通讯录需要修改这个变量 @温瑶瑶
        //切分方式需要修改这个变量 @温瑶瑶
        //每部手机导入数量需要修改这个变量 @温瑶瑶
        final ImportMode importMode = new ImportMode();
        JLabel j3 = new JLabel("导入前是否清空通讯录：");
        JRadioButton JRB1 = new JRadioButton("是");
        JRB1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                importMode.setIfClear(true);
            }
        });
        JRadioButton JRB2 = new JRadioButton("否");
        JRB2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                importMode.setIfClear(false);
            }
        });
        JRadioButton JRB3 = new JRadioButton("全部号码导入所有手机");
        JRB3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                importMode.setSplitMode(0);
            }
        });
        JRadioButton JRB4 = new JRadioButton("平均导入每部手机");
        JRB4.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                importMode.setSplitMode(1);
            }
        });
        JRadioButton JRB5 = new JRadioButton("每部手机导入" + 10 + "个");
        JRB5.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                importMode.setSplitMode(2);
                importMode.setNums(10);
            }
        });
        JButton JRB6 = new JButton("提交任务");


        ButtonGroup group1 = new ButtonGroup();


        ButtonGroup group2 = new ButtonGroup();
        //@涂笑   JRB6.addActionListener(new SubmitListener());
        group1.add(JRB1);
        group1.add(JRB2);
        group2.add(JRB3);
        group2.add(JRB4);
        group2.add(JRB5);

        J11.add(j1);
        J11.add(j2);
        J12.add(j3);
        J12.add(JRB1);
        J12.add(JRB2);
        J13.add(JRB3);
        J13.add(JRB4);
        J13.add(JRB5);
        J3.add(JRB6);
        J3.validate();

        JRB6.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        CommandTool.importAddressBook(J1.getSelectedDevices(), phoneNums, importMode.isIfClear(), importMode.getSplitMode(), importMode.getNums());
                    }
                }
        );
    }


    public static void main(String[] arge) {
        new ImportAddressBook();


    }

    public Vector<String[]> readFile(File addressBook) {
        try {
            Vector<String[]> address = new Vector<String[]>();
            BufferedReader reader = new BufferedReader(new FileReader(addressBook));
            String tempString = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                log.info("line " + line + ": " + tempString);
                address.add(new String[]{line + "", tempString});
                line++;
            }
            reader.close();
            return address;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.info("importAddressBook --- file not exists");
        } catch (IOException e) {
            e.printStackTrace();
            log.info("importAddressBook --- file io error");
        }
        return null;
    }
}

// 以JAVAFileFilter类继承FileFilter抽象类,并实现accept()与getDescription()方法.
class JavaFileFilter extends FileFilter {

    String ext;

    public JavaFileFilter(String ext) {
        this.ext = ext;
    }

    /* 在accept()方法中,当程序所抓到的是一个目录而不是文件时,我们返回true值,表示将此目录显示出来. */
    public boolean accept(File file) {
        if (file.isDirectory()) {
            return true;
        }
        String fileName = file.getName();
        int index = fileName.lastIndexOf('.');
        if (index > 0 && index < fileName.length() - 1) {
            // 表示文件名称不为".xxx"现"xxx."之类型
            String extension = fileName.substring(index + 1).toLowerCase(); // 取得文件后缀名
            // 若所抓到的文件扩展名等于我们所设置要显示的扩展名(即变量ext值),则返回true,表示将此文件显示出来,否则返回true.
            if (extension.equals(ext))
                return true;
        }
        return false;
    }

    // 实现getDescription()方法,返回描述文件的说明字符串!!!
    public String getDescription() {
        if (ext.equals("java"))
            return "JAVA Source File(*.java)";
        if (ext.equals("class"))
            return "JAVA Class File(*.class)";
        return "";
    }


}
